package top.littlejiang.onlinexam.common.configuration;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import top.littlejiang.onlinexam.entity.OlexamTask;

import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * @author chen
 * @Description
 * @since 2021/4/2 13:50
 */
@Configuration
@EnableScheduling
@Slf4j
public class TaskConfig implements SchedulingConfigurer {

    private volatile ScheduledTaskRegistrar registrar;
    private ConcurrentHashMap<String, ScheduledFuture<?>> scheduledFutures = new ConcurrentHashMap<>();
    private ConcurrentHashMap<String, CronTask> cronTasks = new ConcurrentHashMap<>();

    @Override
    public void configureTasks(ScheduledTaskRegistrar registrar) {
        registrar.setScheduler(new ScheduledThreadPoolExecutor(30));
        this.registrar = registrar;
    }

    /**
     * 删除任务
     * @param taskId
     * @return
     */
    public boolean delete(String taskId){
        if (!Objects.isNull(scheduledFutures.get(taskId))){
            scheduledFutures.get(taskId).cancel(true);
            scheduledFutures.remove(taskId);
            return true;
        }
        return false;
    }

    /**
     * 新增任务
     * @param olexamTask
     * @param task
     */
    public void add(OlexamTask olexamTask, CronTask task){
        ScheduledFuture<?> future = registrar.getScheduler().schedule(task.getRunnable(), task.getTrigger());
        cronTasks.put(olexamTask.getTaskId(), task);
        scheduledFutures.put(olexamTask.getTaskId(), future);
    }

    /**
     * 所有任务id
     * @return
     */
    public Set<String> totalTask(){
        return scheduledFutures.keySet();
    }


}
